/**
 * 登陆
 * @author LiQun
 * @date 2021/11/28
 */
const request = require('request');
const fs = require('fs-extra');
const path = require('path');
const http = require('../../utils/http');


module.exports = {
  async login() {
    const config = path.resolve(__dirname, '../../cache/config.json');
    let data = fs.readFileSync(config, 'utf8');
    data = JSON.parse(data);
    const loginResultOutput = data.loginResultOutput
    console.debug("登陆结果输出文件:", loginResultOutput);
    if (fs.existsSync(loginResultOutput)) {
      fs.removeSync(loginResultOutput);
    }
    fs.writeFileSync(loginResultOutput, '', 'utf8');
    const {qrcode} = await http.get(`/v2/login?qr-format=terminal&qr-size=small&result-output=${loginResultOutput}`)
    console.log('请扫描登陆二维码:\n', qrcode);
    const watcher = fs.watch(loginResultOutput, function (change) {
      let data = fs.readFileSync(loginResultOutput, 'utf8');
      const {status, error} = JSON.stringify(data);
      if (status === 'FAIL') {
        console.log(error);
      } else {
        console.log('用户已扫码登陆!');
      }
      watcher._handle.close();
    })
  },
  async isLogin() {
    const result = await http.get(`/v2/islogin`)
    console.log('result', result);
  },
};
